package jstudy.gu.treenode;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jstudy.gu.kit.tree.TreeSearch;
import jstudy.gu.kit.tree.TreeSearch2;

@Service
public class TreeNodeService {

	@Autowired
	private TreeNodeMapper mapper;

	// 递归,完成树形结构,完整的树形结构
	public List<TreeNode> getTree(int parentId) {
		List<TreeNode> roots = mapper.selectByParent(parentId);
		roots.forEach(root -> root.set_children(getTree(root.getId())));
		return roots;
	}

	public List<TreeNode> searchName(String name) {
		List<TreeNode> hps = mapper.selectNameLike(name);
		TreeSearch<TreeNode> t1 = new TreeSearch<>(mapper::selectById, TreeNode::set_children, TreeNode::get_children,
				TreeNode::getId, TreeNode::getParentId, t -> {
					Integer pid = t.getParentId();
					return (pid == null || pid.equals(0));
				});
		return t1.search(hps);
	}

	public List<TreeNode> searchName2(String name) {
		List<TreeNode> hps = mapper.selectNameLike(name);
		TreeSearch2<TreeNode> t1 = new TreeSearch2<>(mapper, "_children", "id", "parentId", 0);
		return t1.search(hps);
	}
}
